<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\helper;

use Yii;

/**
 * URL
 * @author cleverstone
 * @since ym2.0
 */
class Url extends \yii\helpers\Url
{
    /**
     * 绝对URL转完整URL
     * @param string $absoluteUrl 绝对URL
     * @return string
     */
    public static function whole($absoluteUrl)
    {
        if (empty($absoluteUrl)) return null;
        if (strncasecmp($absoluteUrl, 'http', 4) && strncasecmp($absoluteUrl, '//', 2)) {
            return rtrim(Yii::$app->request->getHostInfo(), '/') . '/' . ltrim($absoluteUrl, '/');
        }

        return $absoluteUrl;
    }

    /**
     * 路径转数组选项
     * @param string $path
     * @return array
     */
    public static function pathToArray($path)
    {
        $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
        $options = [
            'IMAGE' => ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'],
            'VIDEO' => ['avi', 'mov', 'rmvb', 'rm', 'flv', 'mp4', '3gp'],
            'AUDIO' => ['cda', 'wav', 'mp3', 'aiff', 'aif', 'mid', 'wma', 'ra', 'vqf', 'ape', 'm4a'],
            'OTHER' => ['zip', 'rar', 'txt', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'log', 'woff', 'woff2', 'csv'],
        ];
        $type = 'OTHER';
        foreach ($options as $key => $item) {
            $item = array_map('strtolower', $item);
            if (in_array($extension, $item)) {
                $type = $key;
                break;
            }
        }

        return [
            'link' => $path,
            'url' => self::whole($path),
            'type' => $type,
            'ext' => $extension,
        ];
    }
}